import 'package:flutter_web_server/ImcludeServer.dart';

class ServerUpload {
  // 处理文件上传
  static Future<Response> upload(Request request) async {
    final contentType = request.headers['content-type'];
    if (contentType == null || !contentType.startsWith('multipart/form-data')) {
      return ServerR(msg: 'miss content-type').toError();
    }

    final mediaType = MediaType.parse(contentType);
    final boundary = mediaType.parameters['boundary'];
    if (boundary == null) {
      return ServerR(msg: 'miss boundary').toError();
    }

    final payload = request.read();
    final bodyStream = MimeMultipartTransformer(boundary).bind(payload);

    String documentPath = await FFPath.getPhoneLocalPath();
    await for (var part in bodyStream) {
      if (part.headers.containsKey('content-disposition')) {
        var contentDisposition = part.headers['content-disposition'];
        var filename = RegExp(r'filename="([^"]*)"').firstMatch(contentDisposition!)?.group(1);

        if (filename == null) {
          return ServerR(msg: 'Missing filename').toError();
        }

        var file = File("$documentPath/music/$filename");
        await file.create(recursive: true);
        var sink = file.openWrite();
        await part.pipe(sink);
        await sink.close();
        print('文件上传成功: ${file.path}');
      }
    }

    return ServerR(msg: '上传成功').toOK();
  }
}
